package com.weather.androidweather;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;

import androidx.core.app.ActivityCompat;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LocationHelper {
    private Context context;
    private LocationManager locationManager;
    private OnLocationResultListener listener;
    private Geocoder geocoder;

    public interface OnLocationResultListener {
        void onSuccess(String city);
        void onFailed(String error);
    }

    public LocationHelper(Context context, OnLocationResultListener listener) {
        this.context = context;
        this.listener = listener;
        this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        this.geocoder = new Geocoder(context, Locale.getDefault());
    }

    public void startLocation() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED && 
            ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            listener.onFailed("需要位置权限");
            return;
        }

        try {
            // 先尝试获取GPS定位
            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (lastKnownLocation != null) {
                getCityFromLocation(lastKnownLocation);
                return;
            }

            // 如果GPS定位不可用，尝试网络定位
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (lastKnownLocation != null) {
                getCityFromLocation(lastKnownLocation);
                return;
            }

            // 如果都没有缓存的位置，请求新的位置更新
            locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    getCityFromLocation(location);
                    locationManager.removeUpdates(this);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {}

                @Override
                public void onProviderEnabled(String provider) {}

                @Override
                public void onProviderDisabled(String provider) {
                    listener.onFailed("位置服务未开启");
                }
            }, Looper.getMainLooper());

        } catch (Exception e) {
            listener.onFailed("获取位置失败：" + e.getMessage());
        }
    }

    private void getCityFromLocation(Location location) {
        try {
            List<Address> addresses = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                1
            );

            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                String city = address.getLocality();
                if (city == null) {
                    city = address.getAdminArea(); // 直辖市可能city为空
                }
                listener.onSuccess(city);
            } else {
                listener.onFailed("无法获取城市信息");
            }
        } catch (IOException e) {
            listener.onFailed("地理编码失败：" + e.getMessage());
        }
    }

    public void stopLocation() {
        if (locationManager != null) {
            locationManager = null;
        }
    }
} 